package com.sugon.controller.spare;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.sugon.annotation.LimitSubmit;
import com.sugon.dao.SparePartConsumRecordDao;
import com.sugon.entity.*;
import com.sugon.modules.sparepart.consts.SparePartsConsumeType;
import com.sugon.service.*;
import com.sugon.utils.PageUtils;
import com.sugon.utils.Query;
import com.sugon.utils.R;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 备件耗用记录Controller
 *
 * @author sugon
 * @date 2022-08-17 09:11:28
 */
@Controller
@RequestMapping("sparepartconsumrecord")
public class SparePartConsumRecordController {

    @Resource
    private SparePartConsumRecordService sparePartConsumRecordService;
    @Resource
    private SpareStorePosService spareStorePosService;
    @Resource
    private DevRepairRecordService repairRecordService;
    @Resource
    private DevMaintenanceTicketService devPmTicketService;
    @Resource
    private DevAmTicketService devAmTicketService;
    @Resource
    private EnergyDevRepairRecordService energyDevRepairRecordService;
    @Resource
    private MaterialRecordService materialRecordService;
    @Resource
    private SparePartConsumRecordDao sparePartConsumRecordDao;
    @Resource
    private DevRetreadRecordService devRetreadRecordService;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);

        List<SparePartConsumRecordEntity> sparePartConsumRecordList = sparePartConsumRecordService.queryList(query);
        int total = sparePartConsumRecordService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(sparePartConsumRecordList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    @ResponseBody
    public R info(@PathVariable("id") String id) {
        SparePartConsumRecordEntity sparePartConsumRecord = sparePartConsumRecordService.queryObject(id);

        return R.ok().put("sparePartConsumRecord", sparePartConsumRecord);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @ResponseBody
    public R save(@RequestBody SparePartConsumRecordEntity sparePartConsumRecord) {
        // 备件耗用类别必填
        String type = sparePartConsumRecord.getType();
        if (StrUtil.isEmpty(type)) {
            return R.error("备件耗用类别必填！");
        }
        // 校验耗用类别是否合法
        if (!StrUtil.equalsAny(type, SparePartsConsumeType.getEnumValues())) {
            return R.error("非法耗用类别！");
        }
        /*
            设备维修、维护、自主维护时换件，只需要从备件清单中选择备件即可
            COMMON耗用时，是从库位选择的，需要走正常出库流程
         */
        if (StrUtil.equals(type, SparePartsConsumeType.COMMON.name())) {
            // 库位必填
            if (StrUtil.isEmpty(sparePartConsumRecord.getPosId())) {
                return R.error("日常消耗时，库位必选！");
            }
            SpareStorePosEntity storePos = spareStorePosService.queryObject(sparePartConsumRecord.getPosId());
            if (storePos == null) {
                return R.error("非法备件库位ID！");
            }
            sparePartConsumRecord.setSparePartId(storePos.getSpareId());
        } else {
            // 工单信息必填
            if (!StrUtil.isAllNotEmpty(sparePartConsumRecord.getType(), sparePartConsumRecord.getBusinessId())) {
                return R.error("工单信息必填！");
            }
            if (SparePartsConsumeType.REPAIR.name().equals(sparePartConsumRecord.getType())) {
                // 校验设备维修记录是否存在
                DevRepairRecordEntity repairRecord = repairRecordService.queryObject(sparePartConsumRecord.getBusinessId());
                if (repairRecord == null) {
                    return R.error("设备维修工单不存在，请确认！");
                }
                // 设备维修时领料单明细必填
                if (StrUtil.isEmpty(sparePartConsumRecord.getMaterialRecordId())) {
                    return R.error("设备维修时，领料明细必填！");
                }
                // 校验领料明细是否存在
                MaterialRecordEntity materialItem = materialRecordService.queryObject(sparePartConsumRecord.getMaterialRecordId());
                if (materialItem == null) {
                    return R.error("领料明细不存在，请确认！");
                }
                sparePartConsumRecord.setDevId(repairRecord.getDevId());
                sparePartConsumRecord.setSparePartId(materialItem.getSpareId());
                sparePartConsumRecord.setTicketCode(repairRecord.getRepairCode());
            }
            if (SparePartsConsumeType.ENERGY_REPAIR.name().equals(sparePartConsumRecord.getType())) {
                EnergyDevRepairRecord repairRecord = energyDevRepairRecordService.queryObject(sparePartConsumRecord.getBusinessId());
                if (repairRecord == null) {
                    return R.error("设备维修工单不存在，请确认！");
                }
                sparePartConsumRecord.setDevId(repairRecord.getDevId());
                sparePartConsumRecord.setTicketCode(repairRecord.getId());
            } else if (SparePartsConsumeType.MAINTENANCE.name().equals(sparePartConsumRecord.getType())) {
                DevMaintenanceTicketEntity maintenanceTicket = devPmTicketService.queryObject(sparePartConsumRecord.getBusinessId());
                if (maintenanceTicket == null) {
                    return R.error("设备维护工单不存在，请确认！");
                }
                // 校验领料明细是否存在
                MaterialRecordEntity materialItem = materialRecordService.queryObject(sparePartConsumRecord.getMaterialRecordId());
                if (materialItem == null) {
                    return R.error("领料明细不存在，请确认！");
                }
                sparePartConsumRecord.setDevId(maintenanceTicket.getDevId());
                sparePartConsumRecord.setSparePartId(materialItem.getSpareId());
                sparePartConsumRecord.setTicketCode(maintenanceTicket.getRepairCode());
            } else if (SparePartsConsumeType.AM.name().equals(sparePartConsumRecord.getType())) {
                DevAmTicketEntity devAmTicket = devAmTicketService.queryObject(sparePartConsumRecord.getBusinessId());
                if (devAmTicket == null) {
                    return R.error("设备自主维护工单不存在，请确认！");
                }
                sparePartConsumRecord.setDevId(devAmTicket.getDevId());
                sparePartConsumRecord.setTicketCode(devAmTicket.getRepairCode());
            } else if (SparePartsConsumeType.SCARP_REPAIR.name().equals(sparePartConsumRecord.getType())) {
                // 校验修旧利废记录是否存在
                DevRetreadRecordEntity retreadRecord = devRetreadRecordService.queryObject(sparePartConsumRecord.getBusinessId());
                if (retreadRecord == null) {
                    return R.error("修旧利废记录不存在！");
                }
                // 校验领料明细是否存在
                MaterialRecordEntity materialItem = materialRecordService.queryObject(sparePartConsumRecord.getMaterialRecordId());
                if (materialItem == null) {
                    return R.error("领料明细不存在，请确认！");
                }
                sparePartConsumRecord.setSparePartId(materialItem.getSpareId());
            }
        }
        // 保存耗用记录
        boolean saveFlag = sparePartConsumRecordService.save(sparePartConsumRecord) > 0;
        Assert.isTrue(saveFlag);
        if (StrUtil.isNotEmpty(sparePartConsumRecord.getPosId())) {
            // 调整领料数
            sparePartConsumRecordService.modifyConsumeNum(sparePartConsumRecord);
        }
        return R.ok();
    }

    /**
     * 更新耗用记录
     */
    @LimitSubmit(key = "updateConsumeRecord:%s")
    @RequestMapping("/update")
    @ResponseBody
    public R update(SparePartConsumRecordEntity sparePartConsumRecord) {
        String id = sparePartConsumRecord.getId();
        if (StrUtil.isEmpty(id)) {
            return R.error("备件耗用记录ID必填！");
        }
        SparePartConsumRecordEntity consumeRecord = sparePartConsumRecordService.queryObject(id);
        if (consumeRecord == null) {
            return R.error("备件耗用记录不存在！");
        }
        // 领用数不得小于0
        if (sparePartConsumRecord.getNum() <= 0) {
            return R.error("使用数量必须大于0！");
        }
        /*
            如果是设备维修
         */
        if (StrUtil.equalsAny(consumeRecord.getType(), SparePartsConsumeType.REPAIR.name(), SparePartsConsumeType.MAINTENANCE.name())) {
            Assert.notEmpty(consumeRecord.getMaterialRecordId());
            MaterialRecordEntity materialItem = materialRecordService.queryObject(consumeRecord.getMaterialRecordId());
            Assert.notNull(materialItem);
            // 本次的领用数不得大于可用数
            int sumConsumeNum = sparePartConsumRecordDao.sumConsumeNum(id, consumeRecord.getMaterialRecordId());
            if (sparePartConsumRecord.getNum() > materialItem.getActualNum() - sumConsumeNum) {
                return R.error("当前领料明细中最大可以更换数为" + (materialItem.getActualNum() - sumConsumeNum) + " ，请确保使用数量不得大于该数！");
            }
        } else if (SparePartsConsumeType.ENERGY_REPAIR.name().equals(consumeRecord.getType())) {
            if (StrUtil.isNotEmpty(consumeRecord.getPosId())) {
                SpareStorePosEntity position = spareStorePosService.queryObject(consumeRecord.getPosId());
                Assert.notNull(position);
                if (sparePartConsumRecord.getNum() > position.getAvailableNum()) {
                    return R.error("当前备件库位可用库存数不足，请确认！");
                }
            }
        }
        consumeRecord.setNum(sparePartConsumRecord.getNum());
        return sparePartConsumRecordService.modifyConsumeNum(consumeRecord) ? R.ok() : R.error("修改失败，请稍后重试！");
    }

    /**
     * 删除
     */
    @LimitSubmit(key = "deleteConsumeRecord:%s")
    @RequestMapping("/delete")
    @ResponseBody
    public R delete(@RequestBody String[] ids) {
        sparePartConsumRecordService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public R queryAll(@RequestParam Map<String, Object> params) {

        List<SparePartConsumRecordEntity> list = sparePartConsumRecordService.queryList(params);

        return R.ok().put("list", list);
    }
}
